﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Gueei.Gallery.Web.ValidationAttributes
{
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
	public class DependentRequiredAttribute : ValidationAttribute
	{
		private const string DefaultErrorMessage = "Field '{0}' is required";

		public string Property { get; private set; }
		public string DependsOn { get; private set; }
		public bool RequiredIfDependentIsTrue { get; private set; }

		public DependentRequiredAttribute(string property, string dependsOn, bool requiredIfDependentIsTrue)
			: base(DefaultErrorMessage)
		{
			Property = property;
			DependsOn = dependsOn;
			RequiredIfDependentIsTrue = requiredIfDependentIsTrue;
		}

		public override string FormatErrorMessage(string name)
		{
			return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, Property);
		}

		public override bool IsValid(object value)
		{
			var properties = TypeDescriptor.GetProperties(value);
			var propValue = properties.Find(Property, true);
			if (propValue.GetValue(value) != null) return true;
			var depValue = properties.Find(DependsOn, true);
			return !RequiredIfDependentIsTrue.Equals(depValue.GetValue(value));
		}
	}
}